<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref } from "vue";
import {
  ReportPageResponse,
  UpdateReportCommand,
  updateReportApi
} from "@/api/airport/safetyManage/report.api";
import { ElMessage, FormInstance, FormRules } from "element-plus";

interface Props {
  modelValue: boolean;
  row?: ReportPageResponse;
  deptTree?: any[]; // 接收部门树数据
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const formData = reactive<UpdateReportCommand>({
  reportId: 0,
});

const rules: FormRules = {
  acceptDeptId: [{ required: true, message: "请选择处理部门", trigger: "change" }]
};

const formRef = ref<FormInstance>();

function handleOpened() {

  if (props.row) {
    formData.reportId = props.row.reportId;
  } else {
    formRef.value?.resetFields();
  }
}

const loading = ref(false);

async function handleConfirm() {
  try {
    loading.value = true;
    if (!formRef.value) return;
    await formRef.value.validate();
    // 调用更新接口
    await updateReportApi(formData);
    ElMessage.success("转发成功");
    visible.value = false;
    emits("success");
  } catch (e) {
    console.error(e);
    ElMessage.error((e as Error)?.message || "转发失败");
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <v-dialog
    show-full-screen
    :fixed-body-height="false"
    use-body-scrolling
    :title="'确认转发'"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    @opened="handleOpened"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form-container"
    >
      <el-form-item label="处理单位" prop="acceptDeptId">
        <el-cascader
          v-model="formData.acceptDeptId"
          :options="props.deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择部门"
          class="!w-[200px]"
        />
      </el-form-item>
    </el-form>
  </v-dialog>
</template>

<style scoped>
.form-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
}
.form-item {
  margin-bottom: 20px;
}
</style>
